<template>
  <!-- 新建场次 -->
  <div class="scheme-model">
    <el-dialog v-model="dialogVisible" :before-close="handleClose">
      <template #header>
        <div class="my-header">
          <div>新建场次</div>
        </div>
      </template>
      <div class="scheme-box">
        <el-form
          ref="ruleForm2Ref"
          :model="basic2Form"
          :rules="rulesCc"
          label-width="auto"
          class="demo-ruleForm"
          status-icon
        >
          <el-form-item label="场次名称：" prop="ccName">
            <el-input class="width195" v-model="basic2Form.ccName" />
          </el-form-item>
          <el-form-item label="预报时间：" prop="fcTime">
            <el-date-picker
              v-model="basic2Form.fcTime"
              type="datetime"
              placeholder="预报时间"
              @change="changefcTime"
            />
          </el-form-item>
          <el-form-item label="预热期：" prop="yrPerd">
            <el-input class="width80" v-model="basic2Form.yrPerd" @input="handleTime" />小时
          </el-form-item>
          <el-form-item label="预见期：" prop="yjPerd">
            <el-input class="width80" v-model="basic2Form.yjPerd" @input="handleTime" />小时
          </el-form-item>
          <el-form-item label="开始时间：" prop="startTime">
            <el-date-picker
              v-model="basic2Form.startTime"
              type="datetime"
              placeholder="开始时间"
              disabled
            />
          </el-form-item>
          <el-form-item label="结束时间：" prop="endTime">
            <el-date-picker
              v-model="basic2Form.endTime"
              type="datetime"
              placeholder="结束时间"
              disabled
            />
          </el-form-item>
          <el-form-item label="场次编号：" prop="ccCode">
            <el-input class="width195" v-model="basic2Form.ccCode" disabled />
          </el-form-item>
          <el-form-item label="降雨接入类型：" prop="rains">
            <el-select
              v-model="basic2Form.rains.type"
              class="m-2"
              placeholder="选择降雨接入类型"
              size="large"
            >
              <el-option label="选择数据表数据" value="1" />
              <el-option label="导入降雨数据" value="2" />
            </el-select>
            <div class="magLeft" v-if="basic2Form.rains.type == 1">
              <!-- <el-button type="primary">检测雨量数据</el-button> -->
            </div>
            <div class="magLeft" v-if="basic2Form.rains.type == 2">
              <el-upload
                :file-list="fileList"
                class="upload-demo left-spacing"
                action="#"
                multiple
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :limit="3"
                :on-exceed="handleExceed"
                :http-request="uploadRainFile"
                :show-file-list="false"
              >
                <el-button type="primary">导入</el-button>
              </el-upload>
              <el-button type="warning" @click="handleLoadRain">下载雨量模板</el-button>
            </div>
          </el-form-item>
          <el-form-item label="流量接入类型：" prop="flows">
            <el-select
              v-model="basic2Form.flows.type"
              class="m-2"
              placeholder="选择检验成果流量类型"
              size="large"
            >
              <el-option label="选择实测数据表流量" value="1" />
              <el-option label="导入校验流量" value="2" />
            </el-select>
            <div class="magLeft" v-if="basic2Form.flows.type == 1">
              <!-- <el-button type="primary">检测流量数据</el-button> -->
            </div>
            <div class="magLeft" v-if="basic2Form.flows.type == 2">
              <el-upload
                :file-list="fileList"
                class="upload-demo left-spacing"
                action="#"
                multiple
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :limit="3"
                :on-exceed="handleExceed"
                :http-request="uploadFlowFile"
                :show-file-list="false"
              >
                <el-button type="primary">导入</el-button>
              </el-upload>

              <el-button type="warning" @click="handleLoadFlow">下载流量模板</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="handleSave">保存</el-button>
          <el-button @click="handleClose()">取消</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 弹窗 -->
    <ConfigParagm
      :dialogVisible="showDialog"
      @closeDialog="closeDig"
      :paramsDetail="paramsDetail"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, defineExpose } from 'vue'
import ConfigParagm from '../configParagm/index.vue'
import {
  getXajParamSchemes,
  getXajParamsDetail,
  addSkbyCount,
  addXajCount
} from '@/services/modules/model-config'
import { resourcesUp } from '@/services/modules/home'
const props = defineProps({
  watershedId: {
    type: Number,
    default: 1
  },
  modelObj: {
    type: Object,
    default: {}
  }
})
//查看参数详情
let paramsDetail = ref({})
let showDialog = ref(false)
const paramsId = ref(0)
const paramsOptions = ref([])
onMounted(() => {})
const dialogVisible = ref(false)
const ruleForm2Ref = ref(null)
let basic2Form = ref({
  ccCode: '',
  ccName: '',
  fcTime: '',
  startTime: '',
  endTime: '',
  yrPerd: '',
  yjPerd: '',
  rains: {
    //接入降雨类型 1：选择实测降雨，2：录入降雨数据
    type: '1',
    valsPath: ''
    // vals: []
  },
  flows: {
    //接入流量类型 1：选择实测流量，2：录入流量数据
    type: '1',
    valsPath: ''
    // vals: []
  }
})
const rulesCc = {
  ccName: [{ required: true, message: '请输入场次名称', trigger: 'blur' }],
  fcTime: [{ required: true, message: '请选择预报时间', trigger: 'blur' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'blur' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'blur' }],
  yrPerd: [{ required: true, message: '请输入预热期', trigger: 'blur' }],
  yjPerd: [{ required: true, message: '请输入预见期', trigger: 'blur' }]
}
const state = reactive({
  scid: '',
  tiemData: ''
})
const nowtime = (time) => {
  var aa = time // 中国标准时间
  var year = aa.getFullYear()
  var month = aa.getMonth() + 1
  month = month > 10 ? month : '0' + month
  var date = aa.getDate()
  date = date > 10 ? date : '0' + date
  var hour = aa.getHours()
  hour = hour > 10 ? hour : '0' + hour
  var minute = aa.getMinutes()
  minute = minute > 10 ? minute : '0' + minute
  var second = aa.getSeconds()
  second = second > 10 ? second : '0' + second
  var bb = year + '-' + month + '-' + date + ' ' + hour + ':' + minute + ':' + second
  return bb
}
// 输入预热期和预见期触发
const handleTime = () => {
  let aTime = new Date(state.tiemData).getTime()
  //
  let yrq = basic2Form.value.yrPerd * 60 * 60 * 1000
  let yjq = basic2Form.value.yjPerd * 60 * 60 * 1000
  basic2Form.value.startTime = aTime - yrq
  basic2Form.value.endTime = aTime + yjq
  let newTime = nowtime(state.tiemData)
  let reg = new RegExp('-', 'g') // 去掉时间里面的 -
  let a = newTime.replace(reg, '')
  let regs = new RegExp(' ', 'g') // 去掉时间里面的空格
  let b = a.replace(regs, '')
  let regss = new RegExp(':', 'g') // 去掉时间里面的冒号
  let c = b.replace(regss, '')
  basic2Form.value.ccCode = c.slice(0, -4)
}
const changefcTime = (e) => {
  state.tiemData = e
  let aTime = new Date(e).getTime()
  let yrq = basic2Form.value.yrPerd * 60 * 60 * 1000
  let yjq = basic2Form.value.yrPerd * 60 * 60 * 1000
  basic2Form.value.startTime = aTime - yrq
  basic2Form.value.endTime = aTime + yjq
  let newTime = nowtime(e)
  let reg = new RegExp('-', 'g') // 去掉时间里面的 -
  let a = newTime.replace(reg, '')
  let regs = new RegExp(' ', 'g') // 去掉时间里面的空格
  let b = a.replace(regs, '')
  let regss = new RegExp(':', 'g') // 去掉时间里面的冒号
  let c = b.replace(regss, '')
  basic2Form.value.ccCode = c.slice(0, -4)
}
const emit = defineEmits(['closeDialog'])
const closeDialog = () => {
  emit('closeDialog', false)
}
//验证
const rules = {
  name: [{ required: true, message: '请输入方案名称', trigger: 'blur' }],
  region: [
    {
      required: true,
      message: '请选择模型参数',
      trigger: 'change'
    }
  ]
}
//新安江参数方案下拉框绑定
function paramSchemes(blkcd) {
  getXajParamSchemes({
    blkcd: blkcd,
    mid: 2 //todo
    // mid: props.modelobj.id //todo
  }).then((res) => {
    if (res.code === 200) {
      paramsOptions.value = res.data
      paramsId.value = res.data[0].id
      // handleClickUnit(0)
    }
  })
}
const lookConfig = (e) => {
  getXajParamsDetail({
    scid: basicForm.region
  }).then((res) => {
    if (res.code === 200) {
      paramsDetail.value = res.data
      if (res.data) {
        showDialog.value = true
      }
    }
  })
}
//流量导入
async function uploadFlowFile(params) {
  let { file } = params
  let formData = new FormData()
  formData.append('file', file)
  let res = await resourcesUp(formData)
  if (res.code == 200) {
    basic2Form.value.flows.valsPath = res.data.path
    // form1.attachId = res.data.id
    // attachUrl.value = res.data.url
  }
}
// uploadRainFile
//雨量导入
async function uploadRainFile(params) {
  let { file } = params
  let formData = new FormData()
  formData.append('file', file)
  let res = await resourcesUp(formData)
  if (res.code == 200) {
    basic2Form.value.rains.valsPath = res.data.path
    // form1.attachId = res.data.id
    // attachUrl.value = res.data.url
  }
}
//下载流量模版
function handleLoadFlow() {
  let a = document.createElement('a')
  a.href = `/files/副本流量数据模板.xlsx`
  a.download = '副本流量数据模板.xlsx'
  a.click()
}
//下载雨量模版
function handleLoadRain() {
  let a = document.createElement('a')
  a.href = `/files/副本雨量数据模板.xlsx`
  a.download = '副本雨量数据模板.xlsx'
  a.click()
}
//保存区域
function handleSave() {
  ruleForm2Ref.value.validate(async (valid) => {
    console.log(props.modelObj, '11')
    if (valid) {
      console.log(basic2Form, '888888888222')
      const month = (basic2Form.value.fcTime.getMonth() + 1).toString().padStart(2, '0')
      const day = basic2Form.value.fcTime.getDate().toString().padStart(2, '0')
      const year = basic2Form.value.fcTime.getFullYear().toString()
      basic2Form.value.fcTime = `${year}-${month}-${day}`
      basic2Form.value.scid = state.scid
      // basic2Form.value.ccCode = basic2Form.value.ccCode.slice(0, -6)

      if (basic2Form.value.rains.type == 1) {
        basic2Form.value.rains.valsPath = ''
      }
      if (basic2Form.value.flows.type == 1) {
        basic2Form.value.flows.valsPath = ''
      }
      // addForm.startSec = addForm.startSec.join(',')
      // addForm.zoneId = props.watershedId

      if (props.modelObj.id == 2) {
        addXajCount(basic2Form.value).then((res) => {
          if (res.code === 200) {
            console.log(res)
            handleClose()
            closeDialog()
          }
        })
      } else if (props.modelObj.id == 1) {
        addSkbyCount(basic2Form.value).then((res) => {
          if (res.code === 200) {
            console.log(res)
            handleClose()
            closeDialog()
          }
        })
      }
    } else {
      return
    }
  })
}
const closeDig = (v) => {
  showDialog.value = v
}
function handleOpenModal(value) {
  state.scid = value
  dialogVisible.value = true
  paramSchemes(value.blkcd)
}
defineExpose({ handleOpenModal })

function handleClose() {
  dialogVisible.value = false
  ruleForm2Ref.value.resetFields()
}
</script>

<style lang="less" scoped>
.magLeft {
  margin-left: 20px;
  display: flex;
  div {
    margin-right: 10px;
  }
}
.scheme-model {
  .my-header {
    height: 35px;
    border-bottom: 2px solid #eee;
  }
  .link-tag {
    color: #0054db;
    text-decoration: underline;
    margin-left: 10px;
    cursor: pointer;
  }
  .width80 {
    width: 180px;
    margin-right: 20px;
  }
  // .width195 {
  //   width: 200px;
  // }
}
</style>
